﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Diagnostics.Contracts;

namespace FoundationLib.Web.Mvc
{
	public class FieldIdentifierQueue
	{
		private string key;
		private HttpContextBase httpContext;
		private string propertyName;
		private Queue<string> queue;

		[ContractInvariantMethod]
		private void ObjectInvariant()
		{
			Contract.Invariant(this.queue != null);
			Contract.Invariant(this.httpContext != null);
			Contract.Invariant(this.httpContext != null);
			Contract.Invariant(!String.IsNullOrWhiteSpace(this.key));
		}

		public FieldIdentifierQueue(HttpContextBase httpContext, string propertyName, string key)
		{
			Contract.Requires(httpContext != null);
			Contract.Requires(!String.IsNullOrWhiteSpace(propertyName));

			this.httpContext = httpContext;
			this.propertyName = propertyName;
			this.key = key;

			this.queue = (Queue<string>)this.httpContext.Items[this.key];
			if (this.queue == null)
			{
				this.queue = new Queue<string>();
				this.httpContext.Items[key] = this.queue;
				string usedIds = this.httpContext.Request[this.propertyName + ".index"];
				if (!String.IsNullOrEmpty(usedIds))
				{
					foreach (string id in usedIds.Split(','))
					{
						this.queue.Enqueue(id);
					}
				}
			}
		}

		public int Count
		{
			get
			{
				return this.queue.Count;
			}
		}

		public string Dequeue()
		{
			return this.queue.Dequeue();
		}
	}
}
